$(function () {
    var params = getParams();

    getDetailsById(params.id);

    $('#add').tap(addShopcart);

    $("#goBuy").tap(function(){
        var id = params.id;
        window.location.href = "confirm_order.html?id="+id;
    });

    function addShopcart() {
        var id = params.id;
        var price = $('#price').text();
        if (!id) {
            alert('你添加了错误的产品ID');
            return false;
        }
        var option = {
            type: 'post',
            url: Api.detailsUrl,
            data: {
                postType: 'add',
                id: id,
                price: price,
            }
        }
        requestEvent(option).then(addResponse)
    }

    function addResponse(data) {
        alert(data.msg);
    }

    function getDetailsById(id) {
        if (id) {
            var option = {
                type: 'get',
                url: Api.detailsUrl,
                data: {
                    getType: 'getDetail',
                    id: id
                }
            };
            requestEvent(option).then(detailsFn)
        }
    }

    function detailsFn(data) {
        createProductHtml(data[0]);
    }

    function getParams() {
        var params = window.location.search;
        var obj = {};
        if (params) {
            params = params.replace('?', '').split('&');
            for (var i = 0, n = params.length; i < n; i++) {
                var key = params[i].split('=')[0];
                var val = params[i].split('=')[1];
                obj[key] = decodeURIComponent(val);
            }
        }
        return obj;
    }

    function createProductHtml(data) {
        var str = '';
        str += '<div class="deta-img-bc">'
            + '<img src="' + data.img_src + '" alt="tu">'
            + '</div>'
            + '<h2>' + data.title + data.subtitle + '</h2>'
            + '<h3>￥<span id="price">' + data.price + '</span></h3>'
            + '<h4><i>快递: <span>0.00</span></i> <i>月销<span>' + data.sales + '</span>笔</i> <b>广州天河</b></h4>'
        $('#dataPro').html(str);
    }


});